<template>
  <div class="face-page">
    <el-card title="人脸识别系统">
      <!-- 摄像头区域 -->
      <div
        class="camera-box"
        style="position: relative; width: 640px; margin: 0 auto"
      >
        <video
          ref="video"
          autoplay
          playsinline
          muted
          width="640"
          height="480"
          class="camera-preview"
        ></video>
        <!-- 人脸框（动态绘制） -->
        <canvas
          ref="faceCanvas"
          width="640"
          height="480"
          style="position: absolute; top: 0; left: 0; pointer-events: none"
        ></canvas>
      </div>

      <!-- 操作按钮 -->
      <div class="btn-group" style="text-align: center; margin: 20px 0">
        <el-button
          type="primary"
          @click="startCamera"
          :disabled="isCameraActive"
        >
          开启摄像头
        </el-button>
        <el-button
          type="success"
          @click="handleRegister"
          :disabled="!isCameraActive"
        >
          注册人脸
        </el-button>
        <el-button
          type="info"
          @click="handleIdentify"
          :disabled="!isCameraActive"
        >
          识别人脸
        </el-button>
        <el-button
          type="danger"
          @click="stopCamera"
          :disabled="!isCameraActive"
        >
          关闭摄像头
        </el-button>
      </div>

      <!-- 识别结果 -->
      <div v-if="resultVisible" class="result-card">
        <el-tabs type="border-card">
          <el-tab-pane label="识别结果">
            <el-descriptions column="1" border v-if="userInfo">
              <el-descriptions-item label="用户ID">{{
                userInfo.userId
              }}</el-descriptions-item>
              <el-descriptions-item label="用户名">{{
                userInfo.userName
              }}</el-descriptions-item>
              <el-descriptions-item label="真实姓名">{{
                userInfo.nickName
              }}</el-descriptions-item>
              <el-descriptions-item label="所属部门">{{
                userInfo.deptName
              }}</el-descriptions-item>
              <!-- <el-descriptions-item label="角色">{{
                userInfo.roleNames
              }}</el-descriptions-item> -->
              <el-descriptions-item label="匹配度"
                >{{ (matchScore || 0).toFixed(2) }}分</el-descriptions-item
              >
            </el-descriptions>
            <el-alert
              v-else
              :message="resultMsg"
              :type="resultType"
              show-icon
            ></el-alert>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import { registerFace, identifyUser } from "@/api/system/face";

export default {
  data() {
    return {
      isCameraActive: false,
      videoStream: null,
      userInfo: null,
      matchScore: 0,
      resultMsg: "",
      resultType: "info",
      resultVisible: false,
      canvasCtx: null,
    };
  },
  mounted() {
    // 初始化Canvas
    this.canvasCtx = this.$refs.faceCanvas.getContext("2d");
  },
  methods: {
    // 开启摄像头
    startCamera() {
      navigator.mediaDevices
        .getUserMedia({ video: { width: 640, height: 480 } })
        .then((stream) => {
          this.$refs.video.srcObject = stream;
          this.videoStream = stream;
          this.isCameraActive = true;
          this.resultVisible = false;
        })
        .catch((err) => {
          this.$message.error("摄像头访问失败：" + err.message);
        });
    },

    // 关闭摄像头
    stopCamera() {
      if (this.videoStream) {
        this.videoStream.getTracks().forEach((track) => track.stop());
        this.isCameraActive = false;
        this.clearCanvas();
      }
    },

    // 捕获图像转为Base64
    captureImage() {
      const canvas = document.createElement("canvas");
      canvas.width = 640;
      canvas.height = 480;
      canvas.getContext("2d").drawImage(this.$refs.video, 0, 0, 640, 480);
      return canvas.toDataURL("image/jpeg").split(",")[1]; // 去除前缀
    },

    // 注册人脸
    handleRegister() {
      const imageBase64 = this.captureImage();
      registerFace({ imageBase64 }).then((res) => {
        if (res.data.success == true) {
          this.$message.success("人脸注册成功");
        } else {
          this.$message.error(res.data.msg || "注册失败");
        }
      });
    },

    // 识别人脸
    handleIdentify() {
      const imageBase64 = this.captureImage();
      identifyUser({ imageBase64 }).then((res) => {
        this.resultVisible = true;
        if (res.data.success == true) {
          this.userInfo = res.data.userInfo;
          this.matchScore = res.data.score;
          this.resultType = "success";
          this.resultMsg = "识别成功";
          this.$message.success("识别成功");
        } else {
          this.userInfo = null;
          this.resultType = "error";
          this.resultMsg = res.data.msg || "识别失败";
          this.$message.error("识别失败");
        }
      });
    },

    // 清除Canvas绘制
    clearCanvas() {
      this.canvasCtx.clearRect(0, 0, 640, 480);
    },
  },
  beforeDestroy() {
    this.stopCamera();
  },
};
</script>

<style scoped>
.face-page {
  padding: 20px;
}
.camera-preview {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}
.btn-group .el-button {
  margin: 0 10px;
}
.result-card {
  margin-top: 20px;
}
</style>
